package fsu.cs.cis5930;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import fsu.cs.cis5930.GameEngine.BombSpace;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

/**
 * This activity represents the actual game board.
 *
 */
public class GameActivity extends Activity {
	String TAG = "GameActivity";
	private GameEngine engine;
	private Settings gameSettings;
	private GridView gridview;
	private BombAdapter i;
	private Handler createBombHandler;
	private Handler endGameHandler;

	/** Generates a bomb every x seconds. */
	private Timer bombTimer;
	
	/** Creates a bomb every time this passes. */
	private long CREATE_BOMB_EVERY_X_SECONDS = 3000;		
	
	MediaPlayer mp; 
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        
        engine = (GameEngine) getApplicationContext();
	    gameSettings = engine.getSettings();
	    engine.startGame();
	    
        gridview = (GridView) findViewById(R.id.game);
        gridview.setNumColumns( gameSettings.getMaxY() );
      
        i = new BombAdapter(this);
        gridview.setAdapter(i);
        engine.setGameBoard(i);
       
        mp = MediaPlayer.create(this, R.raw.game);
     
        createBombHandler = new Handler() { 
        	@Override public void handleMessage(Message msg) 
        	{ i.createBomb(Bomb.Type.NORMAL);
        		if (engine.getScore() % 10 == 5)
        			i.createBomb(Bomb.Type.NORMAL);
        	  i.notifyDataSetChanged();
        	}
        };
        
        final MediaPlayer mp2= MediaPlayer.create(this, R.raw.gameover);
        endGameHandler = new Handler() { 
        	@Override public void handleMessage(Message msg) 
        	{
        		bombTimer.cancel();
    			i.diffuseAll();
      	      	mp.release();
        	try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}

              mp2.start();
        	}
        };
	    
        engine.setEndGame(endGameHandler);
	    OnItemClickListener mOnClickGridCell = new OnItemClickListener() {
	    	@Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           
                BombAdapter im = (BombAdapter) parent.getAdapter();
                BombSpace space = im.getItem(position);
                Bomb bomb = space.getBomb();
                if (bomb.getType() != Bomb.Type.EMPTY)
                {
                	engine.increaseScore();
	                bomb.diffuse();
	                im.addEmptyCell(space);
	                im.notifyDataSetChanged();
                }
            }
        };
        
        gridview.setOnItemClickListener(mOnClickGridCell);
    }
    public void onStart()
    {
    	super.onStart();
    	
		
    }
    
    public void onPause()
    {
    	super.onPause();
    	bombTimer.cancel();
    	mp.release();
    }
    
    public void onDestroy()
    {
    	super.onDestroy();
    	i.diffuseAll();
    }
    
    
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	//Create a bomb every x seconds.
		bombTimer = new Timer();
		bombTimer.schedule(new TimerCreateBomb(), CREATE_BOMB_EVERY_X_SECONDS);
		
		mp.start();
    }
    
   
	private class TimerCreateBomb extends TimerTask
	{
		@Override
		public void run() {
			createBombHandler.sendEmptyMessage(0);
			if ( gameSettings.getConnectionType() == Connection.Type.SINGLE_PLAYER)
				{
				if (CREATE_BOMB_EVERY_X_SECONDS > 1000)
					CREATE_BOMB_EVERY_X_SECONDS -= 120;
				else if ( CREATE_BOMB_EVERY_X_SECONDS > 650)
					CREATE_BOMB_EVERY_X_SECONDS -= 11;
				else if ( CREATE_BOMB_EVERY_X_SECONDS > 200)
					CREATE_BOMB_EVERY_X_SECONDS -= 5;
				}
				
			bombTimer.schedule(new TimerCreateBomb(), CREATE_BOMB_EVERY_X_SECONDS);}	}
    
    public class BombAdapter extends BaseAdapter {
        private Context mContext;
        private List<BombSpace> cells;
        private List<BombSpace> emptyCells;

        public BombAdapter(Context c) {
            mContext = c;
            cells = new ArrayList<BombSpace>();
            emptyCells = new ArrayList<BombSpace>();
            for (Integer i = 0; i < gameSettings.getMaxY() * gameSettings.getMaxX(); i++)
            {
            	BombSpace space = new BombSpace(c);
            	addView( space );
            	emptyCells.add( space );
            }
        }

        public int getCount() {
            return cells.size();
        }
        
        public Context getContext()
        { return mContext;}

        public BombSpace getItem(int position) {
            return cells.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        public void addView(BombSpace v)
        {
        	cells.add(v);
        }
        
        
        public void addEmptyCell(BombSpace space)
        {
        	emptyCells.add(space);
        }
        
        public BombSpace getEmptySpace()
        {
        	if ( emptyCells.isEmpty())
        		return null;
        	
        	Collections.shuffle(emptyCells);
        	return emptyCells.get(0);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            
            if (convertView == null) {  // if it's not recycled, initialize some attsributes
            	convertView = getItem(position);
            	convertView.setLayoutParams(new GridView.LayoutParams(parent.getWidth()/gameSettings.getMaxY()-5, parent.getHeight()/gameSettings.getMaxX()-10));
            	convertView.setPadding(0, 0, 0, 0);
            	return convertView;
            }             
            
            return getItem(position);
        }

		public void createBomb(Bomb.Type bType) {
			BombSpace target = getEmptySpace();
			if (target == null)
				return;
			emptyCells.remove(target);
			MediaPlayer mp1 = MediaPlayer.create(mContext, R.raw.placebomb);
			mp1.start();
			target.addView( new Bomb(mContext, bType));
			
		}
		
		public void diffuseAll()
		{
			for ( BombSpace b : cells)
			{
				b.getBomb().diffuse();
			}
			
		}

    }
}

